#include "ui.h"
#include "ui_custom.h"
#include <time.h>
#include <sys/time.h>
#include <stdio.h>

// 添加外部声明
extern int hazard_warning_state;
extern lv_timer_t *hazard_warning_timer;

int current_speed = 0;               // 初始化速度值为0
float current_coolant_temp = 40.0f;  // 初始化冷却液温度为40°C
float current_rpm = 0.0f;            // 初始化转速值为0.0 (1000/min)
float current_fuel = 1.0f;           // 默认值，实际值将从文件中读取
bool is_manual_temp_set = false;     // 初始化温度为自动控制模式
bool is_manual_rpm_set = false;      // 初始化转速度为自动控制模式
bool is_manual_fuel_set = false;     // 初始化油量为自动控制模式

// 读取油量数据
static float read_fuel_data(void) {
    FILE *fp = fopen("/mnt/fuel_data.txt", "r");
    if (fp == NULL) {
        return 1.0f;  // 如果文件不存在，返回默认值1.0f
    }
    
    float fuel;
    if (fscanf(fp, "%f", &fuel) != 1) {
        fuel = 1.0f;  // 读取失败，返回默认值
    }
    
    fclose(fp);
    return fuel;
}

// 保存油量数据
static void save_fuel_data(float fuel) {
    FILE *fp = fopen("/IOT/fuel_data.txt", "w");
    if (fp == NULL) {
        return;  // 打开文件失败，直接返回
    }
    
    fprintf(fp, "%.2f", fuel);
    fflush(fp);
    fclose(fp);
}


void start_animations(void)
{
    // 先初始化所有指针到正确位置
    lv_img_set_angle(ui_speedline, 0);        // 速度表指针归零
    lv_img_set_angle(ui_rpmline, 0);          // 转速表指针归零
    lv_img_set_angle(ui_Coolline, 300);       // 温度表指针指向40度
    current_fuel = read_fuel_data();          //  从文件中读取油量值

    // 然后设置初始值
    set_speed_value(current_speed);          // 设置初始速度值
    set_rpm_value(current_rpm);              // 设置初始转速值
    set_fuel_value(current_fuel);
    set_coolant_temp(current_coolant_temp);  // 设置初始冷却液温度
    
}

// 初始化所有警告灯为半透明状态
void init_warning_lights(void)
{
    lv_obj_set_style_opa(ui_Coolant_Temperature_Warning_Light, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_ABS_Warning_Light, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_Brake_System_Warning_Light, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_Low_Fuel_Warning, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_Door_Open_Warning_Light, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_Airbag_Warning_Light, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_Seat_Belt_Warning_Light, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_High_Beam_Headlights, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_Low_Beam_Headlights, LV_OPA_50, 0);
    lv_obj_set_style_opa(ui_Hazard_Warning_Lights, LV_OPA_50, 0);
}

// 重置所有警告灯状态
void reset_all_warnings(void)
{
    set_coolant_temperature_warning(false);
    set_abs_warning(false);
    set_brake_warning(false);
    set_fuel_warning(false);
    set_door_warning(false);
    set_airbag_warning(false);
    set_seatbelt_warning(false);
    set_high_beam(false);
    set_low_beam(false);
    set_hazard_warning(false);
}


void update_time_display(void) {  // 更新时间显示
    time_t rawtime;
    struct tm *timeinfo;
    char time_str[9];
    
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(time_str, sizeof(time_str), "%H:%M:%S", timeinfo);
    lv_label_set_text(ui_time_label, time_str);
}



// 冷却液温度警告灯控制
void set_coolant_temperature_warning(bool is_on)
{
    if (is_on) {
        CoolantTemperatureWarningLight_Animation(ui_Coolant_Temperature_Warning_Light, 0);
    } else {
        lv_obj_set_style_opa(ui_Coolant_Temperature_Warning_Light, LV_OPA_50, 0);
    }
}

// ABS警告灯控制
void set_abs_warning(bool is_on)
{
    if (is_on) {
        ABSWarningLight_Animation(ui_ABS_Warning_Light, 0);
    } else {
        lv_obj_set_style_opa(ui_ABS_Warning_Light, LV_OPA_50, 0);
    }
}

// 制动系统警告灯控制
void set_brake_warning(bool is_on)
{
    if (is_on) {
        BrakeSystemWarningLight_Animation(ui_Brake_System_Warning_Light, 0);
    } else {
        lv_obj_set_style_opa(ui_Brake_System_Warning_Light, LV_OPA_50, 0);
    }
}

// 燃油不足警告灯控制
void set_fuel_warning(bool is_on)
{
    if (is_on) {
        LowFuelWarning_Animation(ui_Low_Fuel_Warning, 0);
    } else {
        lv_obj_set_style_opa(ui_Low_Fuel_Warning, LV_OPA_50, 0);
    }
}

// 车门开启警告灯控制
void set_door_warning(bool is_on)
{
    if (is_on) {
        DoorOpenWarningLight_Animation(ui_Door_Open_Warning_Light, 0);
    } else {
        lv_obj_set_style_opa(ui_Door_Open_Warning_Light, LV_OPA_50, 0);
    }
}

// 安全气囊警告灯控制
void set_airbag_warning(bool is_on)
{
    if (is_on) {
        AirbagWarningLight_Animation(ui_Airbag_Warning_Light, 0);
    } else {
        lv_obj_set_style_opa(ui_Airbag_Warning_Light, LV_OPA_50, 0);
    }
}

// 安全带警告灯控制
void set_seatbelt_warning(bool is_on)
{
    if (is_on) {
        SeatBeltWarningLight_Animation(ui_Seat_Belt_Warning_Light, 0);
    } else {
        lv_obj_set_style_opa(ui_Seat_Belt_Warning_Light, LV_OPA_50, 0);
    }
}

// 远光灯控制
void set_high_beam(bool is_on)
{
    if (is_on) {
        HighBeamHeadlights_Animation(ui_High_Beam_Headlights, 0);
    } else {
        lv_obj_set_style_opa(ui_High_Beam_Headlights, LV_OPA_50, 0);
    }
}

// 近光灯控制
void set_low_beam(bool is_on)
{
    if (is_on) {
        LowBeamHeadlights_Animation(ui_Low_Beam_Headlights, 0);
    } else {
        lv_obj_set_style_opa(ui_Low_Beam_Headlights, LV_OPA_50, 0);
    }
}

// 危险警告灯控制
void set_hazard_warning(bool is_on)
{
    if (is_on) {
        HazardWarningLights_Animation(ui_Hazard_Warning_Lights, 0);
        // 同时显示左右转向灯
        lv_obj_clear_flag(ui_Left_turn_signal, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(ui_Right_turn_signal, LV_OBJ_FLAG_HIDDEN);
    } else {
        lv_obj_set_style_opa(ui_Hazard_Warning_Lights, LV_OPA_50, 0);
        // 隐藏左右转向灯
        lv_obj_add_flag(ui_Left_turn_signal, LV_OBJ_FLAG_HIDDEN);
        lv_obj_add_flag(ui_Right_turn_signal, LV_OBJ_FLAG_HIDDEN);
    }
}


void set_speed_value(int speed)   // 速度表盘的指针动画
{
    current_speed = speed;  // 更新全局速度值
    
    // 计算对应的角度值 (238度对应220的速度值)
    int angle = (speed * 2380) / 220;  // 注意：SquareLine使用10倍角度值
    
    // 创建动画
    ui_anim_user_data_t * PropertyAnimation_0_user_data = lv_mem_alloc(sizeof(ui_anim_user_data_t));  // 为动画用户数据分配内存
    PropertyAnimation_0_user_data->target = ui_speedline;
    PropertyAnimation_0_user_data->val = -1;
    
    lv_anim_t PropertyAnimation_0;
    lv_anim_init(&PropertyAnimation_0);   // 初始化动画结构体
    lv_anim_set_time(&PropertyAnimation_0, 900);  // 使用原始动画的时间
    lv_anim_set_user_data(&PropertyAnimation_0, PropertyAnimation_0_user_data);
    lv_anim_set_custom_exec_cb(&PropertyAnimation_0, _ui_anim_callback_set_image_angle);  // 动画执行回调：负责更新目标元素的角度（核心逻辑）
    lv_anim_set_values(&PropertyAnimation_0, lv_img_get_angle(ui_speedline), angle);     // 动画起始值和结束值：从指针当前角度（lv_img_get_angle(ui_speedline)）过渡到计算出的angle
    lv_anim_set_path_cb(&PropertyAnimation_0, lv_anim_path_linear);
    lv_anim_set_delay(&PropertyAnimation_0, 0);   
    lv_anim_set_ready_cb(&PropertyAnimation_0, _ui_anim_callback_free_user_data);      // 动画结束回调：释放用户数据内存
    lv_anim_set_playback_time(&PropertyAnimation_0, 0);
    lv_anim_set_playback_delay(&PropertyAnimation_0, 0);
    lv_anim_set_repeat_count(&PropertyAnimation_0, 0);
    lv_anim_set_repeat_delay(&PropertyAnimation_0, 0);
    lv_anim_set_early_apply(&PropertyAnimation_0, false);
    lv_anim_start(&PropertyAnimation_0);

    // 根据速度计算冷却液温度（模拟算法）
    // 基础温度40°C，速度每增加10单位，温度上升8°C
    float simulated_temp = 40.0f + (speed * 8.0f / 10.0f);
    // 限制温度在40-120°C范围内
    simulated_temp = simulated_temp > 120.0f ? 120.0f : simulated_temp;
    simulated_temp = simulated_temp < 40.0f ? 40.0f : simulated_temp;

    // 根据速度计算转速（模拟算法）
    // 基础转速0.0，速度每增加10单位，转速上升0.2
    float simulated_rpm = 0.0f + (speed * 0.2f / 10.0f);
    simulated_rpm = simulated_rpm > 7.0f ? 7.0f : simulated_rpm;
    simulated_rpm = simulated_rpm < 0.0f ? 0.0f : simulated_rpm;

    // 根据速度计算油量（模拟算法）
    // 基础油量1.0，速度每增加10单位，油量减少0.05
    float simulated_fuel = 1.0f - (speed * 0.05f / 10.0f);
    simulated_fuel = simulated_fuel > 1.0f ? 1.0f : simulated_fuel;
    simulated_fuel = simulated_fuel < 0.0f ? 0.0f : simulated_fuel;

    // 只有当手动设置的温度值不存在时，才使用模拟温度
    if (!is_manual_temp_set)
    {
        set_coolant_temp(simulated_temp);   // 自动模式下不受之前的影响直接设置温度
    }

    // 只有当手动设置的转速值不存在时，才使用模拟转速
    if (!is_manual_rpm_set)
    {
        set_rpm_value(simulated_rpm);
    }

    // 只有当手动设置的油量值不存在时，才使用模拟油量
    if (!is_manual_fuel_set)
    {
        set_fuel_value(simulated_fuel);
    }
}

void set_coolant_temp(float temp)   // 冷却液温度表盘的指针动画
{
    current_coolant_temp = temp;  // 更新全局温度值
    
    // 计算对应的角度值 (70度对应80的温度范围：120-40)
    // 起始角度为300度(30度)，结束角度为1000度(100度)
    int angle =300 + ((temp - 40) * 700) / 80;  // 注意：SquareLine使用10倍角度值
    
    // 创建动画
    ui_anim_user_data_t * PropertyAnimation_0_user_data = lv_mem_alloc(sizeof(ui_anim_user_data_t));
    PropertyAnimation_0_user_data->target = ui_Coolline;
    PropertyAnimation_0_user_data->val = -1;
    
    lv_anim_t PropertyAnimation_0;
    lv_anim_init(&PropertyAnimation_0);
    lv_anim_set_time(&PropertyAnimation_0, 1000);  // 使用原始动画的时间
    lv_anim_set_user_data(&PropertyAnimation_0, PropertyAnimation_0_user_data);
    lv_anim_set_custom_exec_cb(&PropertyAnimation_0, _ui_anim_callback_set_image_angle);
    lv_anim_set_values(&PropertyAnimation_0, lv_img_get_angle(ui_Coolline), angle);
    lv_anim_set_path_cb(&PropertyAnimation_0, lv_anim_path_linear);
    lv_anim_set_delay(&PropertyAnimation_0, 0);
    lv_anim_set_ready_cb(&PropertyAnimation_0, _ui_anim_callback_free_user_data);
    lv_anim_set_playback_time(&PropertyAnimation_0, 0);
    lv_anim_set_playback_delay(&PropertyAnimation_0, 0);
    lv_anim_set_repeat_count(&PropertyAnimation_0, 0);
    lv_anim_set_repeat_delay(&PropertyAnimation_0, 0);
    lv_anim_set_early_apply(&PropertyAnimation_0, false);
    lv_anim_start(&PropertyAnimation_0);
    
    // 检查是否需要触发温度报警
    if (temp >= 120.0f) {
        set_coolant_temperature_warning(true);
    } else {
        set_coolant_temperature_warning(false);
    }
}


void set_rpm_value(float rpm)   // 转速表盘的指针动画
{
    current_rpm = rpm;  // 更新全局转速值
    
    // 计算对应的角度值 (225度对应7的转速范围：0-7)
    // 起始角度为0度，结束角度为2250度(225度)
    int angle = (rpm * 2250) / 7;  // 注意：SquareLine使用10倍角度值
    
    // 创建动画
    ui_anim_user_data_t * PropertyAnimation_0_user_data = lv_mem_alloc(sizeof(ui_anim_user_data_t));
    PropertyAnimation_0_user_data->target = ui_rpmline;
    PropertyAnimation_0_user_data->val = -1;
    
    lv_anim_t PropertyAnimation_0;
    lv_anim_init(&PropertyAnimation_0);
    lv_anim_set_time(&PropertyAnimation_0, 1000);  // 使用原始动画的时间
    lv_anim_set_user_data(&PropertyAnimation_0, PropertyAnimation_0_user_data);
    lv_anim_set_custom_exec_cb(&PropertyAnimation_0, _ui_anim_callback_set_image_angle);
    lv_anim_set_values(&PropertyAnimation_0, lv_img_get_angle(ui_rpmline), angle);
    lv_anim_set_path_cb(&PropertyAnimation_0, lv_anim_path_linear);
    lv_anim_set_delay(&PropertyAnimation_0, 0);
    lv_anim_set_ready_cb(&PropertyAnimation_0, _ui_anim_callback_free_user_data);
    lv_anim_set_playback_time(&PropertyAnimation_0, 0);
    lv_anim_set_playback_delay(&PropertyAnimation_0, 0);
    lv_anim_set_repeat_count(&PropertyAnimation_0, 0);
    lv_anim_set_repeat_delay(&PropertyAnimation_0, 0);
    lv_anim_set_early_apply(&PropertyAnimation_0, false);
    lv_anim_start(&PropertyAnimation_0);
}

void set_fuel_value(float fuel)   // 油量表盘的指针动画
{
    current_fuel = fuel;  // 更新全局油量值
    // save_fuel_data(fuel); // 保存油量值到文件

    // 计算对应的角度值 (100度对应1的油量范围：0-1)
    // 起始角度为120度(1200)，结束角度为220度(2200)
    // 修改角度计算，确保在正确范围内
    int start_angle = 2200;                         // 起始角度220度
    int angle_range = 1000;                         // 角度范围100度
    int angle = start_angle - (fuel * angle_range); // 注意：SquareLine使用10倍角度值

    // 如果是第一次设置，直接设置角度而不使用动画
    static bool first_time = true;
    if (first_time)
    {
        lv_img_set_angle(ui_Fuel_line, angle);
        first_time = false;
        return;
    }

        // 创建动画
        ui_anim_user_data_t *PropertyAnimation_0_user_data = lv_mem_alloc(sizeof(ui_anim_user_data_t));
        PropertyAnimation_0_user_data->target = ui_Fuel_line;
        PropertyAnimation_0_user_data->val = -1;

        lv_anim_t PropertyAnimation_0;
        lv_anim_init(&PropertyAnimation_0);
        lv_anim_set_time(&PropertyAnimation_0, 1000); // 使用原始动画的时间
        lv_anim_set_user_data(&PropertyAnimation_0, PropertyAnimation_0_user_data);
        lv_anim_set_custom_exec_cb(&PropertyAnimation_0, _ui_anim_callback_set_image_angle);
        lv_anim_set_values(&PropertyAnimation_0, lv_img_get_angle(ui_Fuel_line), angle);
        lv_anim_set_path_cb(&PropertyAnimation_0, lv_anim_path_linear);
        lv_anim_set_delay(&PropertyAnimation_0, 0);
        lv_anim_set_ready_cb(&PropertyAnimation_0, _ui_anim_callback_free_user_data);
        lv_anim_set_playback_time(&PropertyAnimation_0, 0);
        lv_anim_set_playback_delay(&PropertyAnimation_0, 0);
        lv_anim_set_repeat_count(&PropertyAnimation_0, 0);
        lv_anim_set_repeat_delay(&PropertyAnimation_0, 0);
        lv_anim_set_early_apply(&PropertyAnimation_0, false);
        lv_anim_start(&PropertyAnimation_0);

        // 检查是否需要触发燃油报警
        if (fuel < 0.2f)
        {
            set_fuel_warning(true);
        }
        else
        {
            set_fuel_warning(false);
        }
    }

    void save_fuel_on_exit(void)
    {
        save_fuel_data(current_fuel);
    }